﻿$(document).ready(function () {
    layui.use('table', function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form

        // 渲染表格的函数
        function renderTable(pageNum) {
            // 从查询框获取条件
            var dto = {
                CarriersCode: $("#CarriersCode").val(),
                CarriersName: $("#CarriersName").val(),
                PageIndex: 1,
                PageSize: 100,
                Token: localStorage.getItem("token")
            }
            // 发送Ajax请求
            $.ajax({
                url: '/Carrier/GetCarrierModel',  // 这里填上你的后端接口地址
                type: 'GET',
                data: dto,
                dataType: 'json',
                success: function (response) {
                    var data = JSON.parse(response)
                    // 渲染表格
                    table.render({
                        elem: '#dataTable',
                        cols: [[
                            { type: 'checkbox', fixed: 'left', width: 125},
                            { field: 'carriersCode', align: 'center', title: '承运商编号',width:300 },
                            { field: 'carriersName',align: 'center', title: '承运商名称', width: 300 },
                            { field: 'describe',align: 'center', title: '备注', width: 300 },
                            {
                                fixed: 'right', title: '操作', width: 300, align: 'center', minWidth: 125, templet: function (d) {
                                    return '<a class="layui-btn layui-btn-xs layui-icon layui-icon-edit" lay-on="test-page-custom" onclick="UpdCarrier(' + d.carriersId + ')">编辑</a><a class="layui-btn layui-btn-xs layui-icon layui-icon-delete" onclick="DelCarrier(' + d.carriersId + ')"  lay - event="moredel"> 删除</a > '
                                },
                            }
                        ]],
                        data: data.data.list,  // 数据源
                        page: true,   // 启用分
                        limit: 5,    // 每页显示多少条数据
                        limits: [10, 20, 30],  // 分页选择项
                        curr: pageNum,  // 当前页
                        total: data.data.sumcount,  // 总记录数
                        loading: true, // 启用加载状态
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                    });

                    //// 渲染分页控件
                    var totalPages = Math.ceil(response.totalcount / 10);  // 计算总页数
                    layui.laypage.render({
                        //elem: 'pagination',//上一页
                        count: response.totalcount,  // 总记录数
                        limit: 10,
                        curr: pageNum || 1,
                        jump: function (obj, first) {
                            if (!first) {
                                renderTable(obj.curr);  // 不为第一次调用时，重新渲染表格
                            }
                        }
                    });
                },
                error: function (xhr, status, error) {
                    console.log('请求失败: ' + error);
                }
            });

            ////////////选择复选框之后的数据////////////////////////////////////////////////
            document.getElementById('getCheckData').onclick = function () {
                // 获取所有勾选的行数据
                var checkedData = table.checkStatus('dataTable').data;
                // 提取选中数据的ID
                var checkedIds = checkedData.map(function (item) {
                    return item.carriersId;  // 获取每一行的id
                });
                // 输出选中的ID
                var currentDate = new Date();
                var deldto = {
                    id: checkedIds,
                    delName: "朱泊霖",
                    delTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
                    Token: localStorage.getItem("token")
                }
                console.log(deldto);
                if (deldto.id.length == 0) {
                    layer.msg('批量删除至少选择一项');
                    return
                }
                layer.confirm('你真的要批量删除吗？', { icon: 3 }, function () {
                    $.ajax({
                        url: "/Carrier/DelCarrier",
                        data: deldto,
                        type: "post",
                        success: function (res) {
                            //console.log(res)
                            var s = JSON.parse(res)
                            if (s.data > 0) {
                                layer.msg('批量删除成功', { icon: 0 }, function () {
                                    //layer.msg('提示框关闭后的回调');
                                    location.reload()
                                });
                            }
                            else {
                                layer.msg('批量删除失败');
                                return
                            }
                        }
                    })
                }, function () {
                    layer.msg('取消批量删除');
                })
            }

            ////////////选择复选框编辑////////////////////////////////////////////////
            document.getElementById('piUpd').onclick = function () {
                // 获取所有勾选的行数据
                var checkedData = table.checkStatus('dataTable').data;
                // 提取选中数据的ID
                var checkedIds = checkedData.map(function (item) {
                    return item.carriersId;  // 获取每一行的id
                });
                // 输出选中的ID
                var currentDate = new Date();
                if (checkedIds.length == 0) {
                    layer.msg('编辑至少选择一项');
                    return
                }
                if (checkedIds.length >=2) {
                    layer.msg('编辑只能选择一项');
                    return
                }
                console.log(checkedIds[0]);
                var obj = {
                    carriersId: '',
                    carriersCode: '',
                    carriersName: '',
                    describe: '',
                    office_Id: '',
                    user_Id: '',
                    addName: '',
                    addTime: '',
                    updName: '',
                    updTime: '',
                    delName: '',
                    delTime: ''
                }
                    //反填方法
                    $.ajax({
                        url: "/Carrier/FanCarrier",
                        data: {
                            token: localStorage.getItem("token"),
                            id: checkedIds[0]
                        },
                        type: "get",
                        success: function (res) {
                            var data = JSON.parse(res)
                            $(data.data).each(function () {
                                $("#carriersId").val(this.carriersId)
                                $("#carriersCode").val(this.carriersCode)
                                $("#carriersName").val(this.carriersName)
                                $("#describe").val(this.describe)

                                $("#office_Id").val(this.office_Id)
                                $("#user_Id").val(this.user_Id)
                                $("#addName").val(this.addName)
                                $("#addTime").val(this.addTime)
                                $("#updName").val(this.updName)
                                $("#updTime").val(this.updTime)
                                $("#delName").val(this.delName)
                                $("#delTime").val(this.delTime)

                                var currentDate = new Date();
                                obj.carriersId = this.carriersId;
                                obj.carriersCode = this.carriersCode;
                                obj.carriersName = this.carriersName;
                                obj.describe = this.describe;
                                obj.office_Id = this.office_Id;
                                obj.user_Id = this.user_Id;
                                obj.addName = this.addName;
                                obj.addTime = this.addTime;
                                obj.updName = '卢芳';

                                obj.updTime = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes();
                                obj.delName = this.delName;
                                obj.delTime = this.delTime;


                            })
                        }
                    })
                    //打开弹框
                    layer.open({
                        type: 1,
                        area: '350px',
                        resize: false,
                        shadeClose: true,
                        title: '修改承运商',
                        content: `
                <form class="layui-form" action="">
                    <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
                     <div class="demo-login-container">
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             类型编号： <input type="text" id="carriersCode" name="carriersCodes" value="" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             类型名称：<input type="text" id="carriersName"  name="carriersNames" value="" lay-verify="required" placeholder="全部" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                      <div class="layui-form-item">
                         <div class="layui-input-wrap">
                         备注：<input type="text" id="describe" value="" name="describes" lay-verify="required" placeholder="全部" lay-reqtext="请填写备注" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>

                      <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">确定</button>
              </div>

                     </div>
                   </div>
                </form>
                `,
                        success: function () {
                            var obj1 = {
                                carriersId: '',
                                carriersCode: '',
                                carriersName: '',
                                describe: '',
                                office_Id: '',
                                user_Id: '',
                                addName: '',
                                addTime: '',
                                updName: '',
                                updTime: '',
                                delName: '',
                                delTime: '',
                                Token: ''
                            }
                            // 对弹层中的表单进行初始化渲染
                            form.render();
                            // 表单提交事件
                            form.on('submit(demo-login)', function (data) {
                                var field = data.field; // 获取表单字段值
                                //console.log(JSON.stringify(field));
                                obj1.carriersId = obj.carriersId;
                                obj1.carriersCode = field.carriersCodes;
                                obj1.carriersName = field.carriersNames;
                                obj1.describe = field.describes;
                                obj1.office_Id = obj.office_Id;
                                obj1.user_Id = obj.user_Id;
                                obj1.addName = obj.addName;
                                obj1.addTime = obj.addTime;
                                obj1.updName = '卢芳';
                                var times = new Date();
                                obj1.updTime = times.getFullYear() + '-' + (times.getMonth() + 1) + '-' + times.getDate() + ' ' + times.getHours() + ':' + times.getMinutes();
                                obj1.Token = localStorage.getItem("token");
                                $.ajax({
                                    url: "/Carrier/UpdCarrier",
                                    data: obj1,
                                    type: "put",
                                    success: function (res) {
                                        var s = JSON.parse(res);
                                        if (s.data > 0) {
                                            layer.msg('修改成功', { icon: 0 }, function () {
                                                layer.msg('提示框关闭后的回调');
                                                location.reload()
                                            });
                                        }
                                        else if (s.data == -1) {
                                            layer.msg('类别名称已存在，不能修改');
                                            return
                                        }
                                        else {
                                            layer.msg('修改失败');
                                            return
                                        }
                                    }
                                })

                                //// 显示填写结果，仅作演示用
                                //layer.alert(JSON.stringify(field), {
                                //    title: '当前填写的字段值',
                                //});
                                // 此处可执行 Ajax 等操作
                                // …
                                return false; // 阻止默认 form 跳转

                            });
                        },
                    });

            }

        }
        // 监听全选操作
        form.on('checkbox(check-all)', function (data) {
            var checked = data.elem.checked;  // 获取全选复选框的状态
            table.checkStatus('dataTable').isAll = checked;  // 设置是否全选
            form.render('checkbox');  // 重新渲染表单
        });
        ////////////修改////////////////////////////////////////////////
        var obj = {
            carriersId: '',
            carriersCode: '',
            carriersName: '',
            describe: '',
            office_Id: '',
            user_Id: '',
            addName: '',
            addTime: '',
            updName: '',
            updTime: '',
            delName: '',
            delTime: ''
        }
        window.UpdCarrier = function (d) {
            //反填方法
            $.ajax({
                url: "/Carrier/FanCarrier",
                data: {
                    token: localStorage.getItem("token"),
                    id: d
                },
                type: "get",
                success: function (res) {
                    var data = JSON.parse(res)
                    $(data.data).each(function () {
                        $("#carriersId").val(this.carriersId)
                        $("#carriersCode").val(this.carriersCode)
                        $("#carriersName").val(this.carriersName)
                        $("#describe").val(this.describe)

                        $("#office_Id").val(this.office_Id)
                        $("#user_Id").val(this.user_Id)
                        $("#addName").val(this.addName)
                        $("#addTime").val(this.addTime)
                        $("#updName").val(this.updName)
                        $("#updTime").val(this.updTime)
                        $("#delName").val(this.delName)
                        $("#delTime").val(this.delTime)

                        var currentDate = new Date();
                        obj.carriersId = this.carriersId;
                        obj.carriersCode = this.carriersCode;
                        obj.carriersName = this.carriersName;
                        obj.describe = this.describe;
                        obj.office_Id = this.office_Id;
                        obj.user_Id = this.user_Id;
                        obj.addName = this.addName;
                        obj.addTime = this.addTime;
                        obj.updName = '卢芳';

                        obj.updTime = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes();
                        obj.delName = this.delName;
                        obj.delTime = this.delTime;


                    })
                }
            })


            layer.open({
                type: 1,
                area: '350px',
                resize: false,
                shadeClose: true,
                title: '修改承运商',
                content: `
                <form class="layui-form" action="">
                    <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
                     <div class="demo-login-container">
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             类型编号： <input type="text" id="carriersCode" name="carriersCodes" value="" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             类型名称：<input type="text" id="carriersName"  name="carriersNames" value="" lay-verify="required" placeholder="全部" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                      <div class="layui-form-item">
                         <div class="layui-input-wrap">
                         备注：<input type="text" id="describe" value="" name="describes" lay-verify="required" placeholder="全部" lay-reqtext="请填写备注" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>

                      <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">确定</button>
              </div>

                     </div>
                   </div>
                </form>
                `,
                success: function () {
                    var obj1 = {
                        carriersId: '',
                        carriersCode: '',
                        carriersName: '',
                        describe: '',
                        office_Id: '',
                        user_Id: '',
                        addName: '',
                        addTime: '',
                        updName: '',
                        updTime: '',
                        delName: '',
                        delTime: '',
                        Token:''
                    }
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field; // 获取表单字段值
                        //console.log(JSON.stringify(field));
                        obj1.carriersId = obj.carriersId;
                        obj1.carriersCode = field.carriersCodes;
                        obj1.carriersName = field.carriersNames;
                        obj1.describe = field.describes;
                        obj1.office_Id = obj.office_Id;
                        obj1.user_Id = obj.user_Id;
                        obj1.addName = obj.addName;
                        obj1.addTime = obj.addTime;
                        obj1.updName = '卢芳';
                        var times = new Date();
                        obj1.updTime = times.getFullYear() + '-' + (times.getMonth() + 1) + '-' + times.getDate() + ' ' + times.getHours() + ':' + times.getMinutes();
                        obj1.Token = localStorage.getItem("token");
                        $.ajax({
                            url: "/Carrier/UpdCarrier",
                            data: obj1,
                            type: "put",
                            success: function (res) {
                                var s = JSON.parse(res);
                                if (s.data > 0) {
                                    layer.msg('修改成功', { icon: 0 }, function () {
                                        layer.msg('提示框关闭后的回调');
                                        location.reload()
                                    });
                                }
                                else if (s.data == -1) {
                                    layer.msg('类别名称已存在，不能修改');
                                    return
                                }
                                else {
                                    layer.msg('修改失败');
                                    return
                                }
                            }
                        })

                        //// 显示填写结果，仅作演示用
                        //layer.alert(JSON.stringify(field), {
                        //    title: '当前填写的字段值',
                        //});
                        // 此处可执行 Ajax 等操作
                        // …
                        return false; // 阻止默认 form 跳转

                    });
                },
            });
        }

        ////////////删除////////////////////////////////////////////////
        window.DelCarrier = function (id) {
            var currentDate = new Date();
            var delres = {
                id: id,
                delName: '朱泊霖',
                delTime: currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(),
                Token: localStorage.getItem("token")
            };
            console.log(delres)
            layer.confirm('你真的要删除吗？', { icon: 3 }, function () {
                $.ajax({
                    url: "/Carrier/DelCarrier",
                    data: delres,
                    type: "post",
                    success: function (daa) {
                        var s = JSON.parse(daa)
                        if (s.data == 1) {
                            layer.msg('删除成功', { icon: 0 }, function () {
                                location.reload()
                            });
                            //alert('删除成功');

                        }
                        else {
                            layer.msg('删除失败');
                            return
                        }
                    }
                })
            }, function () {
                layer.msg('取消删除');
            });














        }

        ////////////新增//////////////////////////////////////////////////
        layui.use(function () {
            var $ = layui.$;
            var layer = layui.layer;
            var util = layui.util;
            var form = layui.form;
            // 事件
            util.on('lay-on', {
                'test-page-custom1': function () {
                    layer.open({
                        type: 1,
                        area: '350px',
                        resize: false,
                        shadeClose: true,
                        title: '新增承运商',
                        content: `
          <form class="layui-form" action="">
                    <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
                     <div class="demo-login-container">
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             承运商编号： <input type="text" name="carriersCode" value="" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                       <div class="layui-form-item">
                         <div class="layui-input-wrap">
                             承运商名称：<input type="text" lay-verify="required"  name="carriersName" value="" lay-verify="required" placeholder="全部" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>
                      <div class="layui-form-item">
                         <div class="layui-input-wrap">
                         备注：<input type="text" value="" name="describe" lay-verify="required" lay-reqtext="请填写备注" autocomplete="off" class="layui-input" lay-affix="clear">
                         </div>
                       </div>

                      <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login1">确定</button>
              </div>

                     </div>
                   </div>
                </form>
        `,
                        success: function () {
                            // 对弹层中的表单进行初始化渲染
                            form.render();
                            // 表单提交事件
                            var data = {
                                CarriersId: '',
                                CarriersCode: '',
                                CarriersName: '',
                                Describe: '',
                                office_Id: '',
                                user_Id: '',
                                addName: '',
                                addTime: '',
                                Token: ''
                            };
                            form.on('submit(demo-login1)', function (dates) {
                                var field = dates.field; // 获取表单字段值
                                //var aaa = JSON.parse(field);
                                //console.log(aaa)
                                // 生成6位数
                                var randomNum = Math.floor(100000 + Math.random() * 900000);  // 生成100000到999999之间的随机整数
                                data.CarriersCode = randomNum;
                                data.CarriersName = field.carriersName;
                                data.Describe = field.describe;
                                data.Office_Id = '1';
                                data.User_Id = 1;
                                data.AddName = '张三';
                                var times = new Date();
                                data.AddTime = times.getFullYear() + '-' + (times.getMonth() + 1) + '-' + times.getDate() + ' ' + times.getHours() + ':' + times.getMinutes();
                                data.Token = localStorage.getItem("token");
                                $.ajax({
                                    url: "/Carrier/AddCarrier",
                                    data: {
                                        dto: data
                                    },
                                    type: "post",
                                    success: function (res) {
                                        var res1 = JSON.parse(res)
                                        if (res1.data == 1) {
                                            layer.msg('添加成功', { icon: 0 }, function () {
                                                // layer.msg('提示框关闭后的回调');
                                                location.reload()
                                            });
                                            //alert('添加成功')
                                            
                                        }
                                        else if (res1.data == -1) {
                                            layer.msg('类别名称已存在，不能添加');
                                            return
                                        }
                                        else {
                                            layer.msg('添加失败');
                                            return
                                        }
                                    }
                                })
                                
                                return false; // 阻止默认 form 跳转
                            });
                        }
                    });
                }
            })
        });

        // 初次加载表格数据
        renderTable(1);

        // 查询按钮点击事件
        $('#searchBtn').click(function () {
            renderTable(1);  // 重置为第一页，并重新加载数据
        });

        // 获取选中数据按钮
        $('#getSelected').click(function () {
            var checkStatus = table.checkStatus('dataTable');
            var selectedData = checkStatus.data;  // 获取选中的数据
            console.log(selectedData);  // 打印选中的数据
        });
    });




});